<template>
  <div class="articleCate">
    <MainTabBar
      :editableTabs="editableTabs"
      :editable-tabs-value="editableTabsValue"
      @tabHandleClick="tabHandleClick"
      @removeTab="removeTab"
    >
    </MainTabBar>
    <div class="text">
      <div style="width: 700px; margin-top: 20px" v-if="tabType == 1">
        <el-form
          :model="form"
          ref="form"
          label-width="100px"
          class="demo-ruleForm"
          :rules="rules"
        >
          <el-form-item label="名称" prop="name">
            <el-input
              type="age"
              v-model.trim="form.name"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="别名" prop="alias">
            <el-input
              type="age"
              v-model.trim="form.alias"
              autocomplete="off"
            ></el-input>
          </el-form-item>

          <el-form-item label="背景图片">
           <el-upload
              class="avatar-uploader"
              :action="action"
              :headers="headers"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" alt />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
             <div class="image_operate">
              <el-button size="mini" type="primary" @click="deleteImage" v-if="deleteImageType">删除图片</el-button>
              <div class="deleteImageBut">
              <ChooseImg @cliUrl="cliUrl" />
              </div>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm">提交</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div v-else-if="tabType == 0">
        <div>
          <el-button class="btn" @click="addArticleCate">添加</el-button>
        </div>
        <TableComp
          :table-data="tableData"
          :table-column="tableColumn"
          :modifyType="true"
          @modifyRow="modifyRow"
          @deleteRow="deleteRow"
        ></TableComp>
      </div>
    </div>
  </div>
</template>
<script>
import Api from "../../api/api";
import request from "../../api/request";
import TableComp from "../../common/manage/TableComp.vue";
import MainTabBar from "../../common/manage/MainTabBar.vue";
import Upload from "@common/manage/upload"
import ChooseImg from "../../common/manage/chooseIMG.vue"
import qs from "qs";
export default {
  components: {
    TableComp,
    MainTabBar,
    Upload,
     ChooseImg,
  },
  data() {
    return {
      imageUrl:"",
      action: "",
      headers: {},
      tableData: [],
      tab: "",
      targetName:null,
      tableColumn: [
        {
          label: "名称",
          prop: "name",
        },
        {
          label: "别名",
          prop: "alias",
        },
      ],
      editableTabs: [
        {
          title: "文章分类列表",
          name: "0",
          closable: false,
        },
      ],
      deleteImageType : false,
      editableTabsValue: "0",
      tabIndex: 0,
      form: {},
      rules: {
        name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
        alias: [{ required: true, message: "请输入分类别名", trigger: "blur" }],
      },
      tabType: 0, //标签类型，0为表格显示，1为增加或修改页面
      submitFormType: 0, //保存的类型，0为新增，1为修改
      
    };
  },
  mounted() {
    this.getArticleCateData();
    this.action = Api.uploads;
    // this.headers.Authorization = this.$store.state.token
    this.headers.Authorization = window.localStorage.token
    this.headers.fileUrl = 'articleCate'
  },
  methods: {
    // 图片上传
    handleAvatarSuccess(res, file) {
       this.deleteImageType = true
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.cover_img = res.imgSrc;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG / png格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    cliUrl(item){
      this.imageUrl =Api.API_HEADER+item
      this.form.cover_img = item
    },
    deleteImage(){
       let params = {
        method: "POST",
        url: Api.deleteUploads,
        data: qs.stringify({fileurl:this.form.cover_img}),
      };
      request(params)
        .then((result) => {
          if (result.status == 3) {
            this.$message.error("用户登录失效");
            this.$router.push({ name: "bolgHome" });
          } else if (result.status == 0) {
            this.$message({
              message: "删除成功",
              type: "success",
            });
            this.imageUrl = ""
            this.deleteImageType = false
          }
        })
        .catch((err) => {
        });
    },
    getArticleCateData() {
      let params = {
        method: "GET",
        url: Api.getArticleCate,
      };
      request(params)
        .then((result) => {
          if (result.status == 3) {
            this.$message.error("用户登录失效");
            this.$router.push({ name: "bolgHome" });
          } else if (result.status == 0) {
            this.tableData = result.data;
          }
        })
        .catch((err) => {
        });
    },
    tabHandleClick(tabs) {
      let name = tabs.name;
      this.editableTabsValue = tabs.name;
      let tab;
      this.editableTabs.forEach((item) => {
        if (item.name == name) {
          tab = item;
        }
      });
      if (tab.name == 0) {
        this.tabType = 0;
      } else {
        this.tabType = 1;
        if (!tab.row) {
          this.submitFormType = 0;
          this.form = {};
        } else {
          this.submitFormType = 1;
          this.form = tab.row;
        }
      }
    },
    removeTab(targetName) {
      this.targetName = targetName
      let tabs = this.editableTabs;
      let activeName = this.editableTabsValue;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      }
      this.editableTabsValue = activeName;
      this.editableTabs = tabs.filter((tab) => tab.name !== targetName);
      if (this.editableTabs.length == 1) {
        this.tabType = 0;
      }
    },
    modifyRow(row) {
      for (let i = 0; i < this.editableTabs.length; i++) {
        if (this.editableTabs[i].title.indexOf(row.name) >= 0) {
          return;
        }
      }
      let newTabName = ++this.tabIndex + "";
      let obj = {
        title: row.name + "-修改",
        name: newTabName,
        closable: true,
        row: row,
      };
      this.editableTabs.push(obj);
      this.tabType = 1;
      this.form = row;
      this.submitFormType = 1;
      this.editableTabsValue = newTabName;
      this.imageUrl = Api.API_HEADER + "/" + row.cover_img;
    },
    deleteRow(row) {
      let id = Number(row.id);
      let params = {
        method: "POST",
        url: Api.deleteArticleCate + "/" + id,
        // data:qs.stringify({id})
      };
      request(params)
        .then((result) => {
          if (result.status == 3) {
            this.$message.error("用户登录失效");
            this.$router.push({ name: "bolgHome" });
          } else if (result.status == 0) {
           this.$message({
              message: "删除成功",
              type: "success",
            });
            this.getArticleCateData();
          }else{
             this.$message.error("删除失败");
          }
        })
        .catch((err) => {
        });
    },
    addArticleCate() {
      for (let i = 0; i < this.editableTabs.length; i++) {
        if (this.editableTabs[i].title == "新增") {
          return;
        }
      }
      this.imageUrl=""
      let newTabName = ++this.tabIndex + "";
      let obj = {
        title: "新增",
        name: newTabName,
        closable: true,
      };
      this.editableTabs.push(obj);
      this.form = {};
      this.tabType = 1;
      this.submitFormType = 0;
      this.editableTabsValue = newTabName;
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.submitFormType == 0) {
            this.addArticleCateData();
          } else if (this.submitFormType == 1) {
            this.modifyArticleCateData();
          }
        } else {
          return false;
        }
      });
    },
    addArticleCateData() {
      let { name, alias,cover_img} = this.form;
      let params = {
        method: "POST",
        url: Api.addArticleCate,
        data: qs.stringify({cover_img, name,alias}),
      };
      request(params)
        .then((result) => {
          if (result.status == 3) {
            this.$message.error("用户登录失效");
            this.$router.push({ name: "bolgHome" });
          } else if (result.status == 0) {
            this.$message({
              message: "添加成功",
              type: "success",
            });
            this.getArticleCateData();
            this.removeTab(this.targetName)
          }else{
             this.$message.error("添加失败");
          }
        })
        .catch((err) => {
        });
    },
    modifyArticleCateData() {
      let { name, alias, id,cover_img } = this.form;
      let params = {
        method: "POST",
        url: Api.modifyArticleCate,
        data: qs.stringify({ id, name, alias,cover_img }),
      };
      request(params)
        .then((result) => {
          if (result.status == 3) {
            this.$message.error("用户登录失效");
            this.$router.push({ name: "bolgHome" });
          } else if (result.status == 0) {
           this.$message({
              message: "修改成功",
              type: "success",
            });
            this.getArticleCateData();
            this.removeTab(this.targetName)
          }else{
             this.$message.error("修改失败");
          }
        })
        .catch((err) => {
        });
    },
    resetForm() {
      this.form = {};
    },
    getFile(file){
      this.file = file
    }
  },
};
</script>
<style lang="less" scoped>
.articleCate {
  width: 100%;
  height: 100%;
  .text {
    padding: 20px;
    .btn {
      background-color: #545c64;
      color: #fff;
    }
  }
}
.el-tabs__nav .el-tabs__item:nth-child(1) span {
  display: none;
}
.image_operate{
  float: left;
  .deleteImageBut{
  margin-right: 20px;
  float: left;    
}
}
</style>